package org.lzy.shop.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.lzy.shop.base.BaseViewModel
import org.lzy.shop.response.CouponResponse
import org.lzy.shop.response.GoodsInfoResponse
import org.lzy.shop.response.GoodsSpecResponse
import org.lzy.shop.response.ListDTO
import org.lzy.shop.viewmodel.repository.GoodsRepository
import org.lzy.shop.viewmodel.repository.lmpl.GoodsRepositoryImpl

/**
 * 订单信息的VM层
 */
class GoodInfoModel : BaseViewModel() {
    private val goodsRepository: GoodsRepository = GoodsRepositoryImpl()

    val goodInfoData = MutableLiveData<GoodsInfoResponse?>()
    val goodCommentData = MutableLiveData<MutableList<ListDTO>?>()
    val goodSpecData = MutableLiveData<MutableList<GoodsSpecResponse>?>()
    val couponData = MutableLiveData<CouponResponse?>()



    fun getGoodInfo(id: String): LiveData<GoodsInfoResponse?> {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = goodsRepository.getGoodsInfo(id)
                if (response != null) {
                    goodInfoData.value = response
                } else {
                    goodInfoData.value = null
                    errorMessage.value = "获取商品信息失败"
                }
            } catch (e: Exception) {
                e.printStackTrace()
                goodInfoData.value = null
                errorMessage.value = e.message ?: "获取商品信息失败"
            }
        }
        return goodInfoData
    }

    fun getGoodsSpec(id: Int): LiveData<MutableList<GoodsSpecResponse>?> {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = goodsRepository.getGoodsSpec(id)
                if (response != null) {
                    goodSpecData.value = response
                } else {
                    goodSpecData.value = null
                    errorMessage.value = "获取商品规格失败"
                }
            } catch (e: Exception) {
                e.printStackTrace()
                goodSpecData.value = null
                errorMessage.value = e.message ?: "获取商品规格失败"
            }
        }
        return goodSpecData
    }

    fun getCoupon(): LiveData<CouponResponse?> {
        viewModelScope.launch(Dispatchers.Main) {
            try {
                val response = goodsRepository.getCoupon()
                if (response != null) {
                    couponData.value = response
                } else {
                    couponData.value = null
                    errorMessage.value = "获取优惠券失败"
                }
            } catch (e: Exception) {
                e.printStackTrace()
                couponData.value = null
                errorMessage.value = e.message ?: "获取优惠券失败"
            }
        }
        return couponData
    }
}